package cn.vire.electric.simulation.netty.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

//@Component
@Slf4j
//@Order(10002)
public class NettyUdpApplication implements ApplicationRunner, DisposableBean {

    @Value("${netty.server.part:90}")
    private int nettyServerPort;
    EventLoopGroup bossGroup;
    Bootstrap b;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        NettyUdpApplication.this.run0();
//        new Thread(new Runnable() {//
//            @Override
//            public void run() {
//                try {
//                    NettyUdpApplication.this.run0();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }
    public void run0() throws Exception {
        bossGroup = new NioEventLoopGroup();
        b = new Bootstrap();
        b.group(bossGroup)
                .channel(NioDatagramChannel.class)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel channel) throws Exception {
                        channel.pipeline().addLast(
                                new ChannelDuplexHandler() {
                                    InetSocketAddress remoteAddr = null;
                                    InetSocketAddress localAddress = null;
                                    StringDecoder sd = new StringDecoder(Charset.forName("UTF-8"));
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        DatagramPacket msg1 = (DatagramPacket) msg;
                                        this.remoteAddr = msg1.sender();
                                        this.localAddress = msg1.recipient();
                                        String content = msg1.content().toString(Charset.forName("GB2312"));
                                        ctx.fireChannelRead(content);
                                    }

                                    @Override
                                    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                        InetSocketAddress remoteAddr0 = this.remoteAddr;
                                        NetworkInterface inetAddress = NetworkInterface.getByInetAddress(InetAddress.getByName("10.19.182.43"));
                                        for (InterfaceAddress interfaceAddress : inetAddress.getInterfaceAddresses()) {
                                            if (interfaceAddress.getBroadcast()!=null) {
                                                remoteAddr0 = new InetSocketAddress(interfaceAddress.getBroadcast(), 90);
                                            }
                                        }
                                        DatagramPacket datagramPacket = new DatagramPacket(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap((String) msg), Charset.forName("UTF-8")), remoteAddr0, localAddress);
                                        ctx.writeAndFlush(datagramPacket,promise);
                                    }

                                },
                                new SimpleChannelInboundHandler<String>(){
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                        log.info("udp服务收到数据[{}]",msg);
                                        ctx.writeAndFlush("upd服务器收到数据[" + msg + "]");
                                    }
                                });
                    }

                })
                .option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_SNDBUF, 1024*1024)
                .option(ChannelOption.SO_RCVBUF, 1024*1024)
        ;

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(nettyServerPort); // (7)
        log.info("upd服务监听中...");
    }


    @Override
    public void destroy() throws Exception {
        bossGroup.shutdownGracefully();
        log.info("upd服务关闭...");
    }
}
